/*
 * @lc app=leetcode.cn id=135 lang=javascript
 *
 * [135] 分发糖果
 */

// @lc code=start
/**
 * @param {number[]} ratings
 * @return {number}
 */
var candy = function(ratings) {
  let l2r = [];
  let r2l = [];
  let total = 0;

  for (let i = 0, pre = 1; i < ratings.length; i++) {
    if(ratings[i] > ratings[i-1]) {
      pre = pre + 1;
    } else {
      pre = 1;
    }
    l2r[i] = pre;
  }

  for (let i = ratings.length - 1, pre = 1; i >= 0; i--) {
    if(ratings[i] > ratings[i+1]) {
      pre = pre + 1;
    } else {
      pre = 1;
    }
    r2l[i] = pre;
  }

  for (let i = 0; i < l2r.length; i++) {
    total += Math.max(l2r[i] || 0, r2l[i] || 0);
  }
  return total;
};
// @lc code=end

